#!/bin/bash
exec_name=EttaM1
scripts_dir=$(pwd)
project_dir=${scripts_dir}/..
package_dir=${project_dir}/package
dist_name=${exec_name}-1.0

if [ $# -ge 1 ] && [ -n $1 ]; then
  dist_name=$1
fi

version=$(echo ${dist_name} | sed 's/-/ /g' | awk '{printf $2}')


make_package_control() {
echo "Package: ${exec_name}"
echo "Version: ${version}"
echo "Architecture: amd64"
echo "Maintainer: xliu@ettabiotech.com"
echo "Description: M1 Equipment Software."
}

make_package_preinst() {
echo "#!/bin/bash"
}

make_package_postinst() {
echo "#!/bin/bash"
echo "deb_install_dir=/tmp/${exec_name}/packages"
echo "cur_user=\$(who | awk '{print \$1}')"

echo "cd \${deb_install_dir}/"
echo "tar -zxvf ${dist_name}.tar.gz"

echo "echo start install '${dist_name}'"
echo "script_dir=\${deb_install_dir}/${dist_name}/scripts"
echo "echo 123 | su - \${cur_user} -c \"cd \${script_dir}/;bash install.sh\""
echo "exit_code=\$?"
echo "if [ \$exit_code -eq 0 ]; then"
echo "  echo -e '\033[1;36minfo:\033[0m' \"'${dist_name}' install success.\""
echo "else"
echo "  echo -e '\033[1;31merror:\033[0m' \"'${dist_name}' install fail."\"
echo "fi"

echo "rm -rf \${deb_install_dir}/${dist_name} >/dev/null 2>&1"
echo "exit \$exit_code"
}

make_package_prerm() {
echo '#!/bin/bash'
echo "exec_name=${exec_name}"
echo "cur_user=\$(who | awk '{print \$1}')"
echo 'install_dir=/home/${cur_user}/${exec_name}'

echo '[ x"$1" != x"remove" ] && exit'
echo '[ ! -L ${install_dir}/${exec_name} ] && exit'

echo 'install_version_path=`dirname $(readlink ${install_dir}/${exec_name})`'
echo 'install_version_name=`basename ${install_version_path}`'

echo 'script_dir=${install_version_path}/scripts'
echo 'echo "start uninstall '"'\${install_version_name}'\""
echo 'echo 123 | su - ${cur_user} -c "cd ${script_dir}/;bash uninstall.sh -f;"'
echo 'exit_code=$?'
echo 'if [ $exit_code -eq 0 ]; then'
echo '  echo -e "\033[1;36minfo:\033[0m"' "\"'${dist_name}' uninstall success.\""
echo 'else'
echo '  echo -e "\033[1;31merror:\033[0m"' "\"'${dist_name}' uninstall fail.\""
echo 'fi'
echo 'exit $exit_code'
}

make_package_postrm() {
echo "#!/bin/bash"
}


# build package directory
rm -rf ${package_dir}/ >/dev/null 2>&1
mkdir -p ${package_dir}/DEBIAN/
mkdir -p ${package_dir}/tmp/${exec_name}/packages/

# make package info
make_package_control  > ${package_dir}/DEBIAN/control
make_package_preinst  > ${package_dir}/DEBIAN/preinst
make_package_postinst > ${package_dir}/DEBIAN/postinst
make_package_prerm    > ${package_dir}/DEBIAN/prerm
make_package_postrm   > ${package_dir}/DEBIAN/postrm
chmod 555 ${package_dir}/DEBIAN/pre* ${package_dir}/DEBIAN/post*

# make package data
mv ${project_dir}/${dist_name}.tar.gz ${package_dir}/tmp/${exec_name}/packages/
if [ $? -ne 0 ]; then
  echo -e "\033[1;31merror:\033[0m" "'${dist_name}.tar.gz' not found."
  exit 1
fi

# build package
cd ${project_dir}/
dpkg -b ${package_dir}/ ${dist_name}.deb
